package top.ezzz.config;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import top.ezzz.common.R;
import org.noear.solon.core.route.PathRule;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import top.ezzz.common.UserContext;

/**
 * 用于鉴权
 */
@Component
public class LoginAuth implements RouterInterceptor {

    /**
     * 路径限制规则
     */
    @Override
    public PathRule pathPatterns() {
        return new PathRule().include("/**")
                .exclude("/chats/**") // todo chats测试使用
                .exclude("", "/admin/login")
                .exclude("/doc.html", "/swagger-resources", "/swagger/*");
    }

    /**
     * 拦截处理（包围式拦截） //和过滤器的 doFilter 类似，且只对路由器范围内的处理有效
     */
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        if (null != UserContext.getUser()) {
            chain.doIntercept(ctx, mainHandler);
        } else {
            ctx.render(R.error(401, "账号未登录"));
        }
    }
}
